<script setup lang="ts">
  import { actualCollectPosting } from '@/api/return-factory'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import useRepairGoodListShareData from '@/views/return-factory/repair/detail/composables/useRepairGoodListShareData'
  import _ from 'lodash'
  import { ref, watch } from 'vue'

  const { repairGoodList, clearRepairGoodList } = useRepairGoodListShareData()

  defineOptions({
    name: 'ActualCollectPostingModal',
  })

  const props = defineProps({
    repairId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const visible = defineModel<boolean>('modelValue', { default: false })
  const goodList = ref<Array<ReturnFactoryDetailGood & { actualQty: string }>>([])
  const loading = ref(false)
  const allQtyInputPopoverVisible = ref(false)
  const allActualQty = ref('')

  const hideDialog = () => {
    goodList.value.length = 0
    clearRepairGoodList()
    visible.value = false
  }

  const onPostingClick = () => {
    for (let i = 0; i < goodList.value.length; i++) {
      const good = goodList.value[i]
      if (Number(good.actualQty) !== good.qty) {
        HMessageBox.error('实发数量必须与申请数量一致')
        return
      }
    }

    loading.value = true
    actualCollectPosting(
      goodList.value.map((item) => {
        return {
          goodsNumberInFace: Number(item.actualQty),
          goodsNumberInPlan: item.qty,
          repairGoodsId: item.id,
        }
      }),
      props.repairId,
    )
      .then((res) => {
        if (res.data.code === 20000) {
          emits('update')
          hideDialog()
          HMessage.success('操作成功')
          return
        }

        HMessageBox.error(res.data.message)
      })
      .catch(() => {
        HMessageBox.error('过账失败，请稍后重试')
      })
      .finally(() => {
        loading.value = false
      })
  }

  const onFillApplyQtyToActualQtyClick = () => {
    goodList.value = goodList.value.map((item) => {
      item.actualQty = String(item.qty)
      return item
    })
  }

  const onQtyMultipleConfirmClick = () => {
    allQtyInputPopoverVisible.value = false
    goodList.value = goodList.value.map((item) => {
      item.actualQty = allActualQty.value
      return item
    })
  }

  const onQtyMultipleClick = () => {
    allQtyInputPopoverVisible.value = !allQtyInputPopoverVisible.value
    if (allQtyInputPopoverVisible.value) {
      document.addEventListener('click', onDocumentClick)
    }
  }

  const onDocumentClick = () => {
    allQtyInputPopoverVisible.value = false
  }

  watch(visible, (value) => {
    if (value) {
      goodList.value = _.cloneDeep(
        repairGoodList.value
          .filter((item) => item.status === 9)
          .map((item) => ({ ...item, actualQty: '' })),
      )
    } else {
      document.removeEventListener('click', onDocumentClick)
    }
  })
</script>

<template>
  <h-dialog v-model="visible" title="实收过账" :width="800" :loading="loading">
    <div style="margin-bottom: 8px">
      <h-button type="primary" @click="onFillApplyQtyToActualQtyClick">
        填充申请数量到实收数量
      </h-button>
    </div>
    <el-table :data="goodList" :border="true" :stripe="true" :max-height="400">
      <el-table-column type="index" width="50" :align="'center'" fixed="left" label="序号" />
      <el-table-column label="商品编号" width="100" prop="goodsCode" />
      <el-table-column label="商品名称" show-overflow-tooltip min-width="140" prop="goodsName" />
      <el-table-column label="规格" width="100" prop="goodsSpec" />
      <el-table-column label="型号" width="100" prop="goodsModel" />
      <el-table-column label="申请数量" width="80" prop="qty" />
      <el-table-column label="实收数量" width="140">
        <template #header>
          <div style="display: flex; align-items: center; column-gap: 4px">
            <span>实收数量</span>
            <el-popover :width="196" :visible="allQtyInputPopoverVisible" placement="top">
              <template #reference>
                <h-plain-button :height="20" :padding-lr="6" @click.stop="onQtyMultipleClick">
                  批量
                </h-plain-button>
              </template>

              <div class="all-apply-qty-popover" @click.stop="">
                <el-input
                  v-model.trim.number="allActualQty"
                  style="width: 120px"
                  placeholder="请输入数量"
                />
                <h-plain-button @click="onQtyMultipleConfirmClick">确定</h-plain-button>
              </div>
            </el-popover>
          </div>
        </template>
        <template #default="{ row }">
          <el-input v-model.trim.number="row.actualQty" placeholder="实收数量" />
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <h-button is-modal type="primary" @click="onPostingClick">过账</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-dialog>
</template>

<style scoped lang="scss">
  .all-apply-qty-popover {
    display: flex;
    justify-content: space-between;
  }
</style>
